﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using Server_Monitor.Domain;

namespace Server_Monitor.Controllers
{
    public class ServerController
    {
        private static List<Server> _Servers = new List<Server>();
        static ServerController()
        {
            XmlDocument XDoc = new XmlDocument();
            if (!File.Exists(Program.SERVER_FILE_NAME))
                return;
            XDoc.Load(Program.SERVER_FILE_NAME);
            foreach (XmlNode servers in XDoc.SelectNodes("servers"))
            {
                foreach (XmlNode server in servers.SelectNodes("server"))
                {
                    _Servers.Add(new Server { ServerName = server["name"].InnerText, ServerIP = server["ip"].InnerText });
                }
            }
        }
        public static void AddServers(Server _server)
        {
            _Servers.Add(_server);
        }
        public static void DeleteServer(Server _server)
        {
            _Servers.Remove(_server);
        }
        public static void SaveServers()
        {
            if (File.Exists(Program.SERVER_FILE_NAME))
            {
                File.Delete(Program.SERVER_FILE_NAME);
            }
            StreamWriter rtr = new StreamWriter(Program.SERVER_FILE_NAME);
            rtr.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"+Environment.NewLine+"<servers>");
            foreach (Server server in _Servers)
            {
                rtr.WriteLine("\t<server>" + Environment.NewLine + "\t\t<name>" + server.ServerName + "</name>" + Environment.NewLine + "\t\t<ip>" + server.ServerIP + "</ip>" + Environment.NewLine + "\t</server>");
            }
            rtr.WriteLine("</servers>");
            rtr.Flush();
            rtr.Close();
        }
        public static List<Server> GetServers()
        {
            return _Servers;
        }
    }
}
